package com.pzhu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pzhu.SpringioApplication;
import com.pzhu.entity.Business;
import com.pzhu.entity.User;
import com.pzhu.service.BusinessService;
import com.pzhu.service.UserService;
import com.pzhu.until.JwtTokenUntil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

import static com.pzhu.until.KaptchaUntil.defaultKaptcha;

@RestController
@RequestMapping("/api")
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(SpringioApplication.class);
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessService businessService;

    /**
     * 创建图片验证码
     * @param resp
     * @param session
     * @throws IOException
     */
    @GetMapping(value = "/createImage")
    public void Captcha(HttpServletResponse resp, HttpSession session) throws IOException {
        String code = defaultKaptcha.createText();
        ServletOutputStream outputStream = resp.getOutputStream();
        BufferedImage image = defaultKaptcha.createImage(code);
        //session存储code
        session.setAttribute("code", code);
        log.info("系统的验证码是：" + code);
        ImageIO.write(image, "png", outputStream);
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/profiled")
    public String checkBusiness(HttpServletRequest request) {
        Integer loginBusiness = JwtTokenUntil.getClaim(request, "loginBusiness").asInt();
        Integer loginuser = JwtTokenUntil.getClaim(request, "loginUser").asInt();
        if (loginuser != null) {

            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUserId, loginuser);
            return userService.getOne(userLambdaQueryWrapper).getUserName();
        }
        if (loginBusiness != null) {
            LambdaQueryWrapper<Business> businessLambdaQueryWrapper = new LambdaQueryWrapper<>();
            businessLambdaQueryWrapper.eq(Business::getBusinessId, loginBusiness);
            return businessService.getOne(businessLambdaQueryWrapper).getBusinessName();
        }
        return "请登录";
    }
}
